const db = require('../core/index')
const moment = require('moment')
class cartsController {
    // 添加购物车
    async addCarts (req, res, next) {
        try {
            const queryParams = [
                req.body.pid,
                req.userInfo.u_id,
            ]
            const querySql = 'select * from carts where  p_id=? and u_id=? '
            const queryRes = await db(querySql, queryParams)
            // 判断是在购物车添加过
            if (queryRes.length > 0) {
                const params = [
                    req.body.count,
                    ...queryParams
                ]
                // 购买过
                const updateSpl = 'update carts set p_number = p_number+? , p_total = p_number*p_price where  p_id=? and u_id=?'
                const updateRes = await db(updateSpl, params)
                if (updateRes && updateRes.affectedRows >= 1) {
                    res.json({
                        code: 200,
                        msg: '添加购物车成功u',
                        data: true
                    })
                } else {
                    res.json({
                        code: 1003,
                        msg: '添加购物车失败u',
                        data: false
                    })
                }
            } else {
                const params = [
                    req.body.name,
                    req.body.img,
                    req.body.count,
                    req.body.price,
                    ...queryParams,
                    moment().format('YYYY-MM-DD HH:mm:ss')
                ]
                // 没有购买过
                const insertSpl = 'insert into carts(p_name, p_img, p_number, p_price, p_total, p_id,u_id, p_create) values(?, ?, ?, ?, p_price*p_number, ?, ?, ?)'
                const insertRes = await db(insertSpl, params)
                if (insertRes && insertRes.affectedRows >= 1) {
                    res.json({
                        code: 200,
                        msg: '添加购物车成功a',
                        data: true
                    })
                } else {
                    res.json({
                        code: 1003,
                        msg: '添加购物车失败a',
                        data: false
                    })
                }
            }
        } catch (error) {
            res.json({
                code: 500,
                msg: error.message,
                data: false,
                error
            })
        }
    }
    // 获取当前用户购物车
    async getCartsInfoByUser (req, res, next) {
        try {
            const params = [req.userInfo.u_id]
            console.log('params', params, req.userInfo)
            const querySql = 'select * from carts where u_id=? and p_delete = 1'
            const result = await db(querySql, params)
            if (result && result.length > 0) {
                res.json({
                    code: 200,
                    msg: '获取购物车信息成功',
                    data: result
                })
            } else {
                res.json({
                    code: 200,
                    msg: '购物车为空',
                    data: result
                })
            }
        } catch (error) {
            res.json({
                code: 500,
                msg: '服务器错误',
                data: error.message,
                error
            })
        }
    }
    // 修改数量
    async editCartsNum (req, res, next) {
        try {
            const querySql = 'select p_number from carts  where u_id = ? and c_id = ?'
            const queryParams = [
                req.userInfo.u_id,
                req.body.cid
            ]
            const queryResult = await db(querySql, queryParams)
            console.log('queryResult', queryResult)
            // 先
            if (queryResult && queryResult.length > 0) {
                if (0 >= req.body.count) {
                    res.json({
                        code: 1006,
                        msg: '修改数量不能小于 0 ',
                        data: null
                    })
                } else {
                    const updateSql = 'update carts set p_number=?, p_total = p_number*p_price where c_id = ?'
                    const updateParams = [
                        req.body.count,
                        req.body.cid
                    ]
                    const updateResult = await db(updateSql, updateParams)
                    if (updateResult.affectedRows > 0) {
                        res.json({
                            code: 200,
                            msg: '修改成功',
                            data: true
                        })
                    } else {
                        res.json({
                            code: 1007,
                            msg: '修改失败',
                            data: true
                        })
                    }

                }
            } else {
                res.json({
                    code: 1005,
                    msg: '当前购物车为空，修改失败',
                    data: null
                })
            }
        } catch (error) {
            res.json({
                code: 500,
                msg: error.message,
                data: null,
                error
            })
        }
        // res.send('addcarts')
    }
    // 删除购物车
    async deleteCarts (req, res, next) {
        try {
            const delSql = 'update carts set p_delete = 0 WHERE c_id = ?'
            const params = [req.body.cid]
            const result = await db(delSql, params)
            if (result.affectedRows > 0) {
                res.json({
                    code: 200,
                    msgL: '删除购物车成功',
                    data: true
                })
            } else {
                res.json({
                    code: 1008,
                    msgL: '删除购物车失败',
                    data: false
                })
            }
        } catch (error) {
            res.json({
                code: 500,
                msg: error.message,
                data: null,
                error
            })
        }
    }
    // 结算 把状态1 改成2
    async settleAccounts (req, res, next) {
        try {
            const setSql = 'update carts set p_status = 2 WHERE c_id = ? and p_delete = 1 and p_status != 2'
            const params = [req.body.cid]
            const result = await db(setSql, params)
            if (result.affectedRows > 0) {
                res.json({
                    code: 200,
                    msgL: '结算购物车成功',
                    data: true
                })
            } else {
                res.json({
                    code: 1009,
                    msgL: '结算购物车失败',
                    data: false
                })
            }
        } catch (error) {
            res.json({
                code: 500,
                msg: error.message,
                data: null,
                error
            })
        }
    }
    // 数据库逻辑练习 结算的时候要去对比 数据库的库存跟要结算数量
    async updateCart (req, res, next) {
        try {
            const list = req.body.list
            const cids = list.map(item => item.cid)
            // const cid_sql = cids.map(() => '?').splice(',')
            const queryParams = [
                req.userInfo.u_id,
            ]
            // 先查询要修改的数据列表
            const querySql = `select * from carts  where u_id = ? and c_id in (${cids.splice(',')})`
            const queryResult = await db(querySql, queryParams)
            // 判断 要修改的数据数量是否大于现有数量，使用 throw Error 可以抛出错误中止 forEach 循环 并且阻断后面代码逻辑
            if (queryResult && queryResult.length > 0) {
                queryResult.forEach(item => {
                    list.forEach(c_item => {
                        if (item.c_id === c_item.cid && item.p_number < c_item.count) {
                            throw new Error(`${item.p_name}数量小于要修改的数量`)
                        }
                    })
                })
            }
            console.log('queryResult', queryResult)



            // 批量修改数据
            const sqlPromise = list.map(item => {
                const updateSql = `update carts set p_number = ${item.count} where c_id = ${item.cid}`
                return db(updateSql)
            })
            Promise.all(sqlPromise).then(result => {
                const isSuccess = result.every(item => item.affectedRows > 0)
                console.log(isSuccess)
                if (isSuccess) {
                    res.json({
                        code: 200,
                        msg: '修改成功',
                        data: true
                    })
                } else {
                    res.json({
                        code: 1011,
                        msg: '修改失败',
                        data: true
                    })
                }
            }).catch(error => {
                res.json({
                    code: 500,
                    msg: error.message,
                    data: null,
                    error
                })
            })
            // 先
            // if (queryResult && queryResult.length > 0) {
            //     if (0 >= req.body.count) {
            //         res.json({
            //             code: 1006,
            //             msg: '修改数量不能小于 0 ',
            //             data: null
            //         })
            //     } else {
            //         const updateSql = 'update carts set p_number=?, p_total = p_number*p_price where c_id = ?'
            //         const updateParams = [
            //             req.body.count,
            //             req.body.cid
            //         ]
            //         const updateResult = await db(updateSql, updateParams)
            //         if (updateResult.affectedRows > 0) {
            //             res.json({
            //                 code: 200,
            //                 msg: '修改成功',
            //                 data: true
            //             })
            //         } else {
            //             res.json({
            //                 code: 1007,
            //                 msg: '修改失败',
            //                 data: true
            //             })
            //         }

            //     }
            // } else {
            //     res.json({
            //         code: 1005,
            //         msg: '当前购物车为空，修改失败',
            //         data: null
            //     })
            // }

        } catch (error) {
            console.log('error', error)
            res.json({
                code: 500,
                msg: error.message,
                data: null,
                error
            })
        }
        // res.send('addcarts')
    }
}

module.exports = new cartsController()